import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'dart:ui';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_more_menu_dialog/common_more_menu_dialog.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/media_detail_response_bean.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_library_index_refresh_even.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/terminal_num_update_event.dart';
import 'package:e_reception_flutter/media_library/media_library_index/media_library_index_view_model.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/history_terminal_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/media_add_terminal_by_pic_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/widgets/add_poster_text_dialog.dart';
import 'package:e_reception_flutter/media_library/media_library_index/widgets/set_play_interval_dialog.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/index/bean/index_bind_termainal_info.dart';
import 'package:e_reception_flutter/ui/index/index_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/terminal_detail_info_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/widgets/bubble_widget.dart';
import 'package:e_reception_flutter/utils/file_utils.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_menu_widget/click_back_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/vg_photo_preview.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_save_util_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';
import 'dart:math' as Math;
import 'dart:ui' as ui;

///文件详情页面
class MediaDetailPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "MediaDetailPage";

  final String picid;
  final String id;
  //01播放列表 02资源库
  final String intoflg;
  final String branchname;

  const MediaDetailPage({Key key, this.picid, this.id, this.intoflg, this.branchname}) : super(key: key);

  @override
  _MediaDetailPageState createState() => _MediaDetailPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(
      BuildContext context, String picid, String intoflg, {String id, String branchname}) {
    return RouterUtils.routeForFutureResult(
      context,
      MediaDetailPage(
        picid: picid,
        intoflg: intoflg,
        id: id,
        branchname: branchname,
      ),
      routeName: MediaDetailPage.ROUTER,
    );
  }
}

class _MediaDetailPageState extends BaseState<MediaDetailPage> {

  MediaLibraryIndexViewModel _viewModel;
  String _hsns = "";
  String _startDay = "";
  String _endDay = "";
  bool _urgentFlg = false;
  bool _showUrgentHintFlg = false;
  bool _showUrgentAlarmFlg = true;

  bool showBubble = false;
  double _shrinkOffset = 0.0;
  double _scale = 1.0;
  double _fixScale = 9/16;
  var globalKey = new GlobalKey();

  String _logo;
  bool _transFlag = false;
  StreamSubscription _terminalNumRefreshSubscription;
  int _allTerminalSize = 0;
  String _water;
  @override
  void initState() {
    super.initState();
    String terminalInfoCacheKey = UserRepository.getInstance().getHomePunchAndTerminalInfoCacheKey();
    ///获取缓存数据
    Future<String> terminalInfoFuture = SharePreferenceUtil.getString(terminalInfoCacheKey);
    terminalInfoFuture.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        setState(() {
          Map map = json.decode(jsonStr);
          IndexBindTermainalInfo bean = IndexBindTermainalInfo.fromMap(map);
          if(bean != null){
            if(bean.data != null
                && bean.data.bindTerminalList != null){
              _allTerminalSize = bean.data.bindTerminalList.length;
            }
          }
        });
      }
    });
    _terminalNumRefreshSubscription = VgEventBus.global.streamController.stream.listen((event) {
      if(event is TerminalNumRefreshEvent){
        if((event?.num??0) != 0 && _allTerminalSize == event?.num){
          //数量不变
          print("终端数量未变，不执行");
          return;
        }
        _allTerminalSize = event?.num??0;
      }
    });

    String cacheKey = IndexViewModel.GET_URGENT_API + (UserRepository.getInstance().authId ?? "");
    ///获取缓存数据
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        setState(() {
          if(StringUtils.isNotEmpty(jsonStr)){
            _urgentFlg = (widget?.picid == jsonStr);
            _showUrgentHintFlg = _urgentFlg;
            _showUrgentAlarmFlg = !_urgentFlg;
          }
        });
      }
    });
    VgEventBus.global.streamController.stream.listen((event) {
      if (event is MediaLibraryRefreshEven) {
        _viewModel.getMediaDetail(widget?.picid);
      }
    });
    _viewModel = MediaLibraryIndexViewModel(this);
    _viewModel.getMediaDetail(widget?.picid);
    Future(() {
      VgToolUtils.removeAllFocus(context);
    });

    ComLogoBean logoBean = UserRepository.getInstance().userData.comLogo;
    if(logoBean != null){
      if(StringUtils.isNotEmpty(logoBean.squareTransparentLogo) && "-1" != logoBean.squareTransparentLogo){
        _logo = logoBean.squareTransparentLogo;
        _transFlag = true;
      }else if(StringUtils.isNotEmpty(logoBean.squareOpaqueLogo) && "-1" != logoBean.squareOpaqueLogo){
        _logo = logoBean.squareOpaqueLogo;
      }else{
        _logo = UserRepository.getInstance().getCompanyLogo();
      }
    }else{
      _logo = UserRepository.getInstance().getCompanyLogo();
    }
    if(StringUtils.isNotEmpty(widget?.branchname)){
      _water = widget?.branchname;
    }else{
      _water = UserRepository.getInstance().userData.companyInfo.companynick;
    }
  }

  @override
  void dispose() {
    _terminalNumRefreshSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _scale = ScreenUtils.screenW(context)/375;
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      resizeToAvoidBottomInset: false,
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: _toPlaceHolderWidget(),
    );
  }


  Widget _toPlaceHolderWidget() {
    return ValueListenableBuilder(
        valueListenable: _viewModel?.statusTypeValueNotifier,
        builder:
            (BuildContext context, PlaceHolderStatusType value, Widget child) {
          return VgPlaceHolderStatusWidget(
            loadingStatus: value == PlaceHolderStatusType.loading,
            errorStatus: value == PlaceHolderStatusType.error,
            errorOnClick: () => _viewModel
                .getMediaDetail(widget?.picid),
            loadingOnClick: () => _viewModel
                .getMediaDetail(widget?.picid),
            child: child,
          );
        },
        child: _toInfoWidget());
  }

  Widget _toInfoWidget() {
    return ValueListenableBuilder(
      valueListenable: _viewModel?.mediaDetailValueNotifier,
      builder: (BuildContext context, MediaDetailBean detailBean, Widget child){
        List<AttListBean> attList = (detailBean?.attList != null)?detailBean?.attList:detailBean.usehsnList;
        return Stack(
          children: [
            GestureDetector(
              onTapDown: (details){
                setState(() {
                  showBubble = false;
                });
              },
              onTapUp: (details){
                setState(() {
                  showBubble = false;
                });
              },
              onTapCancel: (){
                setState(() {
                  showBubble = false;
                });
              },
              onPanDown: (details){
                setState(() {
                  showBubble = false;
                });
              },
              child: Column(
                children: <Widget>[
                  _toTopBarWidget(detailBean),
                  _toMediaInfoWidget(detailBean?.comPictureMap, attList),
                  _toContentWidget(detailBean),
                  Visibility(
                      visible: (detailBean?.historyhsnList?.length??0) > 0,
                      child: _toHistoryTerminalWidget(detailBean?.historyhsnList)
                  ),
                  Visibility(
                      visible: (detailBean?.historyhsnList?.length??0) > 0,
                      child: SizedBox(height: 15,)
                  ),
                ],
              ),
            ),
            Visibility(
              visible: showBubble,
              child: Positioned(
                top: 0,
                bottom: 0,
                left: 0,
                right: 0,
                child: GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  onTap: (){
                    setState(() {
                      showBubble = !showBubble;
                    });
                  },
                  child: Container(
                    color: Colors.transparent,
                    child: Stack(
                      children: [
                        Positioned(
                            top: ScreenUtils.getStatusBarH(context) + 44 - 6,
                            right: 15,
                            child: GestureDetector(
                              onTap: ()async{
                                setState(() {
                                  showBubble = !showBubble;
                                });
                                bool result =
                                await CommonConfirmCancelDialog.navigatorPushDialog(context,
                                    title: "提示",
                                    content: "所有终端显示屏中该文件都会删除，且不可找回，确认继续？",
                                    cancelText: "取消",
                                    confirmText: "删除",
                                    confirmBgColor: ThemeRepository.getInstance()
                                        .getMinorRedColor_F95355());
                                if (result ?? false) {
                                  _viewModel?.deleteFolderAndPop(context,
                                      //id
                                      detailBean?.comPictureMap?.id??"",
                                      //视频id
                                      detailBean?.comPictureMap?.videoid??"",
                                      //视频封面or图片地址
                                      detailBean?.comPictureMap?.getToDeletePicUrl(),
                                      //视频地址
                                      (detailBean?.comPictureMap?.isVideo()??false)?(detailBean?.comPictureMap?.picurl??""):"");
                                }
                              },
                              child: BubbleWidget(
                                  120.0,
                                  ((attList?.length??0) > 0)? 111.0:65.0,
                                  ThemeRepository.getInstance().getLineColor_3A3F50(),
                                  BubbleArrowDirection.top,
                                  arrAngle: 85.0,
                                  length: 84.0,
                                  radius: 12.0,
                                  arrHeight: 6.0,
                                  strokeWidth: 0.0,
                                  child: Column(
                                    children: [
                                      ((attList?.length??0) > 0)?
                                      GestureDetector(
                                        behavior: HitTestBehavior.opaque,
                                        onTap: ()async{
                                          setState(() {
                                            showBubble = !showBubble;
                                          });
                                          bool result =
                                          await CommonConfirmCancelDialog.navigatorPushDialog(context,
                                              title: "提示",
                                              content: "仅在当前终端显示屏取消播放，确认不再播放？",
                                              cancelText: "取消",
                                              confirmText: "确定",
                                              confirmBgColor: ThemeRepository.getInstance()
                                                  .getMinorRedColor_F95355());
                                          if (result ?? false) {
                                            String hsns = "";
                                            attList?.forEach((element) {
                                              hsns += element.hsn;
                                              hsns += ",";
                                            });
                                            if(StringUtils.isNotEmpty(hsns)){
                                              hsns = hsns.substring(0, hsns.length-1);
                                            }
                                            _viewModel?.deletePicByHsns(context, detailBean?.comPictureMap?.id??"", hsns);
                                          }
                                        },
                                        child:  SizedBox(
                                          height: 45,
                                          width: 120.0,
                                          child: Center(
                                            child: Text(
                                                '取消播放',
                                                style: TextStyle(
                                                    color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(), fontSize: 14.0
                                                )
                                            ),
                                          ),
                                        ),
                                      ):Container(),
                                      GestureDetector(
                                        behavior: HitTestBehavior.opaque,
                                        onTap: ()async{
                                          setState(() {
                                            showBubble = !showBubble;
                                          });
                                          bool result =
                                          await CommonConfirmCancelDialog.navigatorPushDialog(context,
                                              title: "提示",
                                              content: ((attList?.length??0) > 0)?
                                              "所有终端显示屏中该文件都会删除，且不可找回，确认继续？"
                                                  :"删除后该文件不可找回，确认继续？",
                                              cancelText: "取消",
                                              confirmText: "删除",
                                              confirmBgColor: ThemeRepository.getInstance()
                                                  .getMinorRedColor_F95355());
                                          if (result ?? false) {
                                            _viewModel?.deleteFolderAndPop(context,
                                                //id
                                                detailBean?.comPictureMap?.id??"",
                                                //视频id
                                                detailBean?.comPictureMap?.videoid??"",
                                                //视频封面or图片地址
                                                detailBean?.comPictureMap?.getToDeletePicUrl(),
                                                //视频地址
                                                (detailBean?.comPictureMap?.isVideo()??false)?(detailBean?.comPictureMap?.picurl??""):"");
                                          }
                                        },
                                        child:  Container(
                                          height: 45,
                                          width: 120.0,
                                          alignment: Alignment.center,
                                          child: Text(
                                              '删除文件',
                                              style: TextStyle(
                                                  color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(), fontSize: 14.0
                                              )
                                          ),
                                        ),
                                      ),
                                    ],
                                  )
                              ),
                            )
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _toContentWidget(MediaDetailBean detailBean) {
    List<AttListBean> attList = (detailBean?.attList != null)?detailBean?.attList:detailBean.usehsnList;
    return Expanded(
      child: ScrollConfiguration(
        behavior: MyBehavior(),
        child: NestedScrollView(
          physics: BouncingScrollPhysics(),
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return [
              SliverPersistentHeader(
                delegate: MySliverDelegate(
                    child: _showImageWidget(detailBean),
                    minHeight: 322,
                    maxHeight: 511,
                    stableWidget: _toStableWidget(detailBean?.comPictureMap, attList),
                    shrinkOffsetFunc: (shrinkOffset){
                      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                        setState(() {
                          if(shrinkOffset < 211){
                            _shrinkOffset = shrinkOffset;
                          }else{
                            _shrinkOffset = 211;
                          }
                        });
                      });
                    }
                ),
                pinned: true,
              ),
            ];
          },
          body: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                _playTimeWidget(attList),
                _terminalListWidget(attList),

              ],
            ),
          ),
        ),
      ),
    );
  }

  ///标题栏
  Widget _toTopBarWidget(MediaDetailBean detailBean) {
    return VgTopBarWidget(
      isShowBack: true,
      title: "文件详情",
      rightPadding: 0,
      isHideRightWidget: false,
      rightWidget: Row(
        children: [
          Visibility(
            visible: _showUrgentAlarmFlg && _allTerminalSize > 1 && VgRoleUtils.isSuperAdmin(UserRepository.getInstance().getCurrentRoleId()),
            child: GestureDetector(
              onTap: (){
                setState(() {
                  _showUrgentHintFlg = !_showUrgentHintFlg;
                });
              },
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 15),
                child: Image.asset(
                  "images/icon_open_urgent.png",
                  width: 20,
                ),
              ),
            ),
          ),
          Visibility(
            visible: _showMoreOperations(detailBean),
            child: GestureDetector(
              onTap: () {
                setState(() {
                  showBubble = !showBubble;
                });
              },
              child: Container(
                padding: EdgeInsets.only(right: 15),
                child: Image.asset(
                  "images/icon_more_operations.png",
                  width: 20,
                ),
              ),
            ),
          ),
        ],
      ),
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
    );
  }

  ///历史终端
  Widget _toHistoryTerminalWidget(List<AttListBean> historyhsnList){
    return GestureDetector(
      onTap: (){
        HistoryTerminalPage.navigatorPush(context, historyhsnList);
      },
      child: Container(
        padding: const EdgeInsets.all(15),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              "历史播放终端·${historyhsnList?.length??0}",
              style: TextStyle(
                  color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                  fontSize: 12,
                  height: 1.2
              ),
            ),
            SizedBox(width: 4,),
            Image.asset(
              "images/index_arrow_ico.png",
              width: 6,
              height: 11,
            )
          ],
        ),
      ),
    );
  }

  bool _showMoreOperations(MediaDetailBean detailBean){
    if((UserRepository.getInstance()?.userData?.comUser?.userid) == (detailBean?.comPictureMap?.createuserid??"")
        || VgRoleUtils.isSuperAdmin(UserRepository.getInstance().getCurrentRoleId())){
      return true;
    }
    return false;
  }


  ///文件基本信息栏
  Widget _toMediaInfoWidget(ComPictureMapBean dataBean, List<AttListBean> attList) {
    String startTime = "";
    String endTime = "";
    int totalPlayNum = 0;
    int num = 0;
    if(attList != null && attList.length > 0){
      if(StringUtils.isNotEmpty(attList[0].startday)&&StringUtils.isNotEmpty(attList[0].endday)){
        startTime = attList[0].startday;
        endTime = attList[0].endday;
        int currentMill = DateTime.parse(DateUtil.getDateStrByDateTime(DateTime.now(), format: DateFormat.YEAR_MONTH_DAY)).millisecondsSinceEpoch;
        if(DateTime.parse(startTime).millisecondsSinceEpoch <= currentMill){
          num++;
        }
        for(int i = 1; i < attList.length; i++){
          if(StringUtils.isNotEmpty(attList[i]?.endday) && DateTime.parse(endTime).millisecondsSinceEpoch <= DateTime.parse(attList[i].endday).millisecondsSinceEpoch){
            endTime = attList[i].endday;
          }
          if(StringUtils.isNotEmpty(attList[i]?.startday) && DateTime.parse(startTime).millisecondsSinceEpoch >= DateTime.parse(attList[i].startday).millisecondsSinceEpoch){
            startTime = attList[i].startday;
          }
          if(StringUtils.isNotEmpty(attList[i]?.startday) && DateTime.parse(attList[i].startday).millisecondsSinceEpoch <= currentMill){
            num++;
          }
        }
        int startMill = DateTime.parse(startTime).millisecondsSinceEpoch;
        int endMill = DateTime.parse(endTime).millisecondsSinceEpoch;


        if(endMill > currentMill){
          totalPlayNum = (((currentMill - startMill)~/(1000*3600*24)) + 1);
        }else{
          totalPlayNum = (((endMill - startMill)~/(1000*3600*24)) + 1);
        }
        if(totalPlayNum <= 0){
          totalPlayNum = 0;
        }
      }
    }

    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      padding: EdgeInsets.symmetric(horizontal: 15),
      child: Column(
        children: <Widget>[
          Visibility(
            visible: _showUrgentHintFlg,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(
                  height: 12,
                ),
                Row(
                  children: [
                    Text(
                      "紧急通告模式${(_urgentFlg)?"·已开启":""}",
                      style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          color: (_urgentFlg)
                              ?ThemeRepository.getInstance().getMinorRedColor_F95355()
                              :ThemeRepository.getInstance().getTextMainColor_D0E0F7()
                      ),
                    ),
                    Spacer(),
                    Visibility(
                      visible: VgRoleUtils.isSuperAdmin(UserRepository.getInstance().getCurrentRoleId()),
                      child: GestureDetector(
                        onTap: (){
                          setState(() {
                            (_urgentFlg)?_viewModel.cancelSetPicUrgent(widget?.picid):_viewModel.setPicUrgent(widget?.picid);
                            _urgentFlg = !_urgentFlg;
                            _showUrgentAlarmFlg = !_urgentFlg;
                          });
                        },
                        child: AnimatedSwitcher(
                          duration: DEFAULT_ANIM_DURATION,
                          child: Image.asset(
                            (_urgentFlg)
                                ?"images/icon_urgent_open.png"
                                :"images/icon_urgent_close.png",
                            width: 36,
                            height: 20,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: 4,
                ),
                Text(
                  ( _urgentFlg)?"当前文件持续播放中":"开启紧急通告模式后，您管理的所有终端显示屏将会持续播放当前文件",
                  style: TextStyle(
                      fontSize: 12,
                      color: (_urgentFlg)
                          ?ThemeRepository.getInstance().getMinorRedColor_F95355()
                          :ThemeRepository.getInstance().getTextMainColor_D0E0F7()
                  ),
                ),
                SizedBox(
                  height: 12,
                ),
              ],
            ),
          ),
          Row(
            children: <Widget>[
              Expanded(
                child: Container(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    "尺寸：${dataBean?.picsize?.replaceAll("*", "×")??""}",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 11,
                      color: ThemeRepository.getInstance()
                          .getTextMinorGreyColor_808388(),
                    ),
                  ),
                ),
              ),
              Expanded(
                child: Container(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    "文件大小：${dataBean?.getPicStorageStr()}",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 11,
                      color: ThemeRepository.getInstance()
                          .getTextMinorGreyColor_808388(),
                    ),
                  ),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 4,
          ),
          Row(
            children: <Widget>[
              Expanded(
                child: Container(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    "上传人：${dataBean?.createname??"系统推送"}",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 11,
                      color: ThemeRepository.getInstance()
                          .getTextMinorGreyColor_808388(),
                    ),
                  ),
                ),
              ),
              Expanded(
                child: Container(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    "上传时间：${TimeUtil.formatTimeSimple(dataBean?.bjtime??"")}",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 11,
                      color: ThemeRepository.getInstance()
                          .getTextMinorGreyColor_808388(),
                    ),
                  ),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 4,
          ),
          Row(
            children: <Widget>[
              Container(
                alignment: Alignment.centerLeft,
                child: Text(
                  "已在${num??0}台终端播放${totalPlayNum??0}天",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 11,
                    color: ThemeRepository.getInstance()
                        .getTextMinorGreyColor_808388(),
                  ),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 10,
          ),
        ],
      ),
    );
  }

  Future<String> _save(globalKey) async{
    RenderRepaintBoundary boundary = globalKey.currentContext.findRenderObject();
    ui.Image image = await boundary.toImage();
    ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    Uint8List picBytes = byteData.buffer.asUint8List();
    String imagePath = await FileUtils.createFileFromUnit8List(picBytes);
    return imagePath;
  }

  ///图片展示栏
  Widget _showImageWidget(MediaDetailBean detailBean) {
    double picHeight = 400;
    double picWidth = 224;
    double initialScale = 224/375;
    if (!StringUtils.isEmpty(detailBean?.comPictureMap?.picsize)) {
      List<String> sizeList = detailBean?.comPictureMap?.picsize?.split("*");
      if (int.parse(sizeList[0]) > int.parse(sizeList[1])) {
        picHeight = 400;
      } else {
        picHeight = 400;
      }
    }
    int width = 1;
    int height = 1;
    if(StringUtils.isNotEmpty(detailBean?.comPictureMap?.picsize)){
      width = int.parse(detailBean?.comPictureMap?.picsize?.split("*")[0]);
      height = int.parse(detailBean?.comPictureMap?.picsize?.split("*")[1]);
    }
    VgCacheNetWorkImage image;
    double textWidth;
    double scale = (-(_shrinkOffset - 450)/450)/_scale;
    if(height > width){
      // if(width/height > _fixScale){
      //   //宽较大，固定高度
      //   picHeight = picHeight*_scale;
      //   picWidth = picWidth*_scale*scale;
      //   image = VgCacheNetWorkImage(
      //       detailBean?.comPictureMap?.getCoverUrl() ?? "",
      //       imageQualityType: ImageQualityType.high,
      //       fit: BoxFit.contain,
      //       width: picWidth,
      //       height: picHeight,
      //       placeWidget: Container(color: Colors.black,)
      //   );
      //   picWidth = null;
      //   textWidth = (picHeight * (width/height))*scale;
      // }else{
      //   //高度大，固定宽度
      //   picHeight = picHeight*_scale;
      //   picWidth = picWidth*_scale*scale;
      //   image = VgCacheNetWorkImage(
      //       detailBean?.comPictureMap?.getCoverUrl() ?? "",
      //       imageQualityType: ImageQualityType.high,
      //       fit: BoxFit.cover,
      //       width: picWidth,
      //       placeWidget: Container(color: Colors.black,)
      //   );
      //   textWidth = picWidth;
      // }

      //高度大，固定宽度
      picHeight = picHeight*_scale;
      picWidth = picWidth*_scale*scale;
      image = VgCacheNetWorkImage(
          detailBean?.comPictureMap?.getCoverUrl() ?? "",
          imageQualityType: ImageQualityType.high,
          fit: BoxFit.cover,
          width: picWidth,
          placeWidget: Container(color: Colors.black,)
      );
      textWidth = picWidth;
    }else{
      picHeight = picHeight*_scale;
      picWidth = picHeight*_fixScale*scale;
      image = VgCacheNetWorkImage(
          detailBean?.comPictureMap?.getCoverUrl() ?? "",
          imageQualityType: ImageQualityType.high,
          fit: BoxFit.contain,
          width: picWidth,
          placeWidget: Container(color: Colors.black,)
      );
      textWidth = picWidth;
    }



    return GestureDetector(
      onTap: () async{
        // loading(true);
        // String imagePath = await _save(globalKey);
        // if(StringUtils.isNotEmpty(imagePath)){
        //   loading(false);
        //   VgPhotoPreview.single(context, imagePath,
        //       loadingImageQualityType: ImageQualityType.middleDown);
        // }
        if("01" == detailBean?.comPictureMap?.waterflg
            || StringUtils.isNotEmpty(detailBean?.comPictureMap?.title??"")
            || StringUtils.isNotEmpty(detailBean?.comPictureMap?.subtitle??"")
            || ("00" == detailBean?.comPictureMap?.logoflg && StringUtils.isNotEmpty(_logo))
        ){
          VgPhotoPreview.singleWithWatermarkText(context, detailBean?.comPictureMap?.picurl,
              loadingCoverUrl: detailBean?.comPictureMap?.getCoverUrl(),
              loadingImageQualityType: ImageQualityType.middleDown,
              type: (detailBean?.comPictureMap?.isVideo()??false)?PhotoPreviewType.video:PhotoPreviewType.image,
              extra: {
                "id":detailBean?.comPictureMap?.id,
                "watermark":_water??"",
                "waterflg":detailBean?.comPictureMap?.waterflg,
                "logoflg":detailBean?.comPictureMap?.logoflg,
                "logo":_logo,
                "title":detailBean?.comPictureMap?.title,
                "content":detailBean?.comPictureMap?.subtitle,
              },
              onTextTap: (){
                CommonMoreMenuDialog.navigatorPushDialog(context, {
                  "修改字幕":(){
                    AddPosterTextDialog.navigatorPushDialog(context, title: detailBean?.comPictureMap?.title??"", content: detailBean?.comPictureMap?.subtitle??"",
                        onConfirm: (title, content){
                          _viewModel.addOrEditText(detailBean?.comPictureMap?.id, title, content);
                        },
                        onDelete: (){
                          _viewModel.deleteText(detailBean?.comPictureMap?.id);
                        }
                    );

                  },
                  "删除字幕":()async{
                    bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
                        title: "提示",
                        content: "确认删除字幕？",
                        cancelText: "取消",
                        confirmText: "删除",
                        confirmBgColor:
                        ThemeRepository.getInstance().getMinorRedColor_F95355());
                    if (result ?? false) {
                      _viewModel.deleteText(detailBean?.comPictureMap?.id);
                    }
                  }
                });
              }
          );
        }else{
          VgPhotoPreview.single(context, detailBean?.comPictureMap?.picurl,
              loadingCoverUrl: detailBean?.comPictureMap?.getCoverUrl(),
              loadingImageQualityType: ImageQualityType.middleDown);
        }
      },
      child: Container(
        height: picHeight,
        width: picWidth,
        color: Colors.black,
        child: Stack(
          alignment: Alignment.center,
          children: [
            Stack(
              alignment: Alignment.center,
              children: [
                // VgCacheNetWorkImage(
                //   detailBean?.comPictureMap?.getCoverUrl() ?? "",
                //   imageQualityType: ImageQualityType.middleDown,
                //   width: 224*_scale,
                //   height: 400*_scale,
                // ),
                // Container(
                //   width: 224*_scale,
                //   height: 400*_scale,
                //   child: BackdropFilter(
                //     filter: new ImageFilter.blur(sigmaX: 0, sigmaY: 2),
                //     child: new Container(
                //       // color: Colors.white.withOpacity(0.2),
                //       color: Color(0x33FFFFFF).withOpacity(0.2),
                //       width: 224*_scale,
                //       height: 400*_scale,
                //     ),
                //   ),
                // ),
                image,
              ],
            ),
            Offstage(
              offstage: !(detailBean?.comPictureMap?.isVideo() ?? false),
              child: Opacity(
                opacity: 0.5,
                child: Image.asset(
                  "images/video_play_ico.png",
                  width: 52,
                  fit: BoxFit.contain,
                ),
              ),
            ),
            Align(
              alignment: Alignment.topRight,
              child: Visibility(
                visible: ("00" == (detailBean?.comPictureMap?.logoflg??"") && StringUtils.isNotEmpty(_logo)),
                child: _toLogoWidget(detailBean?.comPictureMap, textWidth, initialScale*scale),
              ),
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Visibility(
                visible: "01" == detailBean?.comPictureMap?.waterflg
                    || StringUtils.isNotEmpty(detailBean?.comPictureMap?.title??"")
                    || StringUtils.isNotEmpty(detailBean?.comPictureMap?.subtitle??""),
                child: _toTextWidget(detailBean?.comPictureMap, textWidth, initialScale*scale),
              ),
            ),
            // Align(
            //   alignment: Alignment.bottomCenter,
            //   child: Visibility(
            //     visible: StringUtils.isEmpty(detailBean?.comPictureMap?.title??"") && StringUtils.isEmpty(detailBean?.comPictureMap?.subtitle??""),
            //     child: _toAddTextWidget(detailBean?.comPictureMap?.id, scale),
            //   ),
            // ),
          ],
        ),
      ),
    );
  }

  ///添加字幕
  Widget _toAddTextWidget(String picid, double scale){
    scale = scale > 1?1:scale;
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        AddPosterTextDialog.navigatorPushDialog(context, title: "", content: "", onConfirm: (title, content){
          _viewModel.addOrEditText(picid, title, content);
        });
      },
      child: Container(
        alignment: Alignment.center,
        width: scale*80,
        height: scale*24,
        margin: EdgeInsets.only(bottom: scale*19),
        decoration: BoxDecoration(
          color: Color(0xB3000000),
          borderRadius: BorderRadius.circular(scale*15),
        ),
        child: Center(
          child: Text(
            "+添加字幕",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
                color: Colors.white,
                fontSize: scale*12,
                height: 1.2
            ),
          ),
        ),
      ),
    );
  }

  Widget _toLogoWidget(ComPictureMapBean comPictureMapBean, double width, double scale){
    scale = scale > 1?1:scale;
    return Container(
      margin: EdgeInsets.all(21*scale),
      child:_transFlag?VgCacheNetWorkImage(
        _logo,
        width: 42*scale,
        height: 42*scale,
        imageQualityType: ImageQualityType.middleUp,
        defaultPlaceType: ImagePlaceType.head,
        defaultErrorType: ImageErrorType.head,
      ):
      Stack(
        alignment: Alignment.center,
        children: [
          Container(
            width: 48*scale,
            height: 48*scale,
            decoration: BoxDecoration(
                color: Color(0x4DFFFFFF),
                borderRadius: BorderRadius.circular(7*scale)
            ),
          ),
          ClipRRect(
            borderRadius: BorderRadius.circular(4*scale),
            child: Container(
              decoration: BoxDecoration(color: Colors.white),
              child: VgCacheNetWorkImage(
                _logo,
                width: 42*scale,
                height: 42*scale,
                fit: BoxFit.contain,
                imageQualityType: ImageQualityType.middleUp,
                defaultPlaceType: ImagePlaceType.head,
                defaultErrorType: ImageErrorType.head,
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _toTextWidget(ComPictureMapBean comPictureMapBean, double width, double scale){
    scale = scale > 1?1:scale;
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if(StringUtils.isEmpty(comPictureMapBean?.title??"") && StringUtils.isEmpty(comPictureMapBean?.subtitle??"")){
          return;
        }
        CommonMoreMenuDialog.navigatorPushDialog(context, {
          "修改字幕":(){
            AddPosterTextDialog.navigatorPushDialog(context, title: comPictureMapBean?.title??"", content: comPictureMapBean?.subtitle??"",
                onConfirm: (title, content){
                  _viewModel.addOrEditText(comPictureMapBean?.id, title, content);
                },
                onDelete: (){
                  _viewModel.deleteText(comPictureMapBean?.id);
                }
            );
          },
          "删除字幕":()async{
            bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
                title: "提示",
                content: "确认删除字幕？",
                cancelText: "取消",
                confirmText: "删除",
                confirmBgColor:
                ThemeRepository.getInstance().getMinorRedColor_F95355());
            if (result ?? false) {
              _viewModel.deleteText(comPictureMapBean?.id);
            }
          }
        });
      },

      child: Container(
        padding: EdgeInsets.symmetric(horizontal: scale*12),
        width: width,
        decoration: (StringUtils.isNotEmpty(comPictureMapBean?.title??"") || StringUtils.isNotEmpty(comPictureMapBean?.subtitle??""))? BoxDecoration(
            gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Color(0x00000000),
                  Color(0x4D000000),
                ]
            )
        ): BoxDecoration(),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: (){

              },
              child: Visibility(
                visible: "01" == comPictureMapBean?.waterflg,
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      alignment: Alignment.center,
                      height: scale*24,
                      padding: EdgeInsets.only(left: scale*6, right: scale*12),
                      decoration: BoxDecoration(
                        color: Color(0x1A000000),
                        borderRadius: BorderRadius.circular(scale*12),
                        border: Border.all(
                            color: Colors.white,
                            width: 0.2),
                      ),
                      child: Text(
                        "· ${_water??""}",
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: scale * 14,
                            height: 1.32
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            SizedBox(height: "01" == comPictureMapBean?.waterflg?scale*6:scale*30,),
            Visibility(
              visible: StringUtils.isNotEmpty(comPictureMapBean?.title??""),
              child: Text(
                comPictureMapBean?.title??"",
                style: TextStyle(
                    color: Colors.white,
                    fontSize: scale*20,
                    fontWeight: FontWeight.w600,
                    height: 1.3
                ),
              ),
            ),
            Visibility(
                visible: StringUtils.isNotEmpty(comPictureMapBean?.title??""),
                child: SizedBox(height: scale*4,)
            ),
            Visibility(
              visible: StringUtils.isNotEmpty(comPictureMapBean?.subtitle??""),
              child: Text(
                comPictureMapBean?.subtitle??"",
                style: TextStyle(
                    color: Colors.white,
                    fontSize: scale*14,
                    height: 1.42
                ),
              ),
            ),
            SizedBox(height: ("01" == comPictureMapBean?.waterflg && StringUtils.isEmpty(comPictureMapBean?.subtitle??""))?scale*6:scale*12,),
          ],
        ),
      ),
    );
  }

  Widget _toStableWidget(ComPictureMapBean comPictureMapBean, List<AttListBean> attList){
    return Column(
      children: [
        SizedBox(height: 17,),
        _toAddTextAndEditTextWidget(comPictureMapBean),
        _terminalWidget(attList)
      ],
    );
  }

  ///添加字幕 添加水印
  Widget _toAddTextAndEditTextWidget(ComPictureMapBean comPictureMapBean){
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Visibility(
          visible: StringUtils.isNotEmpty(_logo),
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: (){
              _viewModel.updateLogo(context, StringUtils.isNotEmpty(widget?.id??"")?widget?.id:widget?.picid, widget?.intoflg, ("01" == comPictureMapBean?.logoflg)?"00":"01");
            },
            child: Container(
              alignment: Alignment.center,
              width: 80,
              height: 24,
              margin: const EdgeInsets.only(bottom: 20),
              decoration: BoxDecoration(
                color: ("00" == comPictureMapBean?.logoflg)?Color(0x33808388):Color(0x331890FF),
                borderRadius: BorderRadius.circular(15),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset(
                    ("00" == comPictureMapBean?.logoflg)?"images/icon_select_watermark.png":"images/icon_unselect_watermark.png",
                    width: 14,
                  ),
                  SizedBox(width: 4,),
                  Text(
                    "添加logo",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: ("00" == comPictureMapBean?.logoflg)?ThemeRepository.getInstance().getTextMinorGreyColor_808388():ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                        fontSize: 12,
                        height: 1.2
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        Visibility(
            visible: StringUtils.isNotEmpty(_logo),
            child: SizedBox(width: 10,)
        ),
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            _viewModel.setWaterFlag(comPictureMapBean?.id, ("01" == comPictureMapBean?.waterflg??"")?"00":"01");
          },
          child: Container(
            alignment: Alignment.center,
            width: 80,
            height: 24,
            margin: const EdgeInsets.only(bottom: 20),
            decoration: BoxDecoration(
              color: ("01" == comPictureMapBean?.waterflg)?Color(0x33808388):Color(0x331890FF),
              borderRadius: BorderRadius.circular(15),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  ("01" == comPictureMapBean?.waterflg)?"images/icon_select_watermark.png":"images/icon_unselect_watermark.png",
                  width: 14,
                ),
                SizedBox(width: 4,),
                Text(
                  "添加水印",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: ("01" == comPictureMapBean?.waterflg)?ThemeRepository.getInstance().getTextMinorGreyColor_808388():ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                      fontSize: 12,
                      height: 1.2
                  ),
                ),
              ],
            ),
          ),
        ),
        SizedBox(width: 10,),
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            AddPosterTextDialog.navigatorPushDialog(context,
                title: comPictureMapBean?.title??"",
                content: comPictureMapBean?.subtitle??"",
                picSize: 1,
                onConfirm: (title, content){
                  _viewModel.addOrEditText(comPictureMapBean?.id, title, content);
                },
                onDelete: (){
                  _viewModel.deleteText(comPictureMapBean?.id);
                }
            );
          },
          child: Container(
            alignment: Alignment.center,
            width: 80,
            height: 24,
            margin: const EdgeInsets.only(bottom: 20),
            decoration: BoxDecoration(
              color: (StringUtils.isNotEmpty(comPictureMapBean?.title??"") || StringUtils.isNotEmpty(comPictureMapBean?.subtitle??""))?Color(
                  0x4D808388):Color(0x331890FF),
              borderRadius: BorderRadius.circular(15),
            ),
            child: Center(
              child: Text(
                (StringUtils.isNotEmpty(comPictureMapBean?.title??"") || StringUtils.isNotEmpty(comPictureMapBean?.subtitle??""))?"修改字幕":"+添加字幕",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    color: (StringUtils.isNotEmpty(comPictureMapBean?.title??"") || StringUtils.isNotEmpty(comPictureMapBean?.subtitle??""))?
                    ThemeRepository.getInstance().getTextMinorGreyColor_808388()
                        :ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                    fontSize: 12,
                    height: 1.2
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  ///播放终端 添加终端
  Widget _terminalWidget(List<AttListBean> attList) {
    return Container(
      height: 50,
      padding: const EdgeInsets.symmetric(horizontal: 15),
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: Row(
        children: <Widget>[
          Text(
            // "终端显示屏·${topInfo?.bindTerminalList?.length ?? 0}",
            "播放终端·${attList?.length??0}",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
                color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                fontSize: 17,
                fontWeight: FontWeight.bold,
                height: 1.22),
          ),
          Spacer(),
          CommonFixedHeightConfirmButtonWidget(
            isAlive: true,
            width: 56,
            height: 24,
            unSelectBgColor: Color(0xFF3A3F50),
            selectedBgColor:
            ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            unSelectTextStyle: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
            ),
            selectedTextStyle: TextStyle(
              color: Colors.white,
              fontSize: 12,
              // fontWeight: FontWeight.w600
            ),
            text: (attList?.length??0) != 0?"修改":"+添加",
            onTap: () async {
              String hsns = "";
              String cantManageHsns = "";
              if(attList != null && attList.length > 0){
                attList.forEach((element) {
                  hsns += element.hsn;
                  hsns += ",";
                  if("00" == (element?.adminflg??"")){
                    cantManageHsns += element.hsn;
                    cantManageHsns += ",";
                  }
                });
              }
              if(StringUtils.isNotEmpty(hsns)){
                hsns = hsns.substring(0, hsns.length-1);
              }
              if(StringUtils.isNotEmpty(cantManageHsns)){
                cantManageHsns = cantManageHsns.substring(0, cantManageHsns.length-1);
              }
              // String result = await MediaSelectTerminalPage.navigatorPush(context, hsns: hsns,
              //     addTerminal: true, startday: _startDay, endday: _endDay, picid: widget?.picid);
              String result = await MediaAddTerminalByPicPage.navigatorPush(context,
                  addTerminal: true, setTimeFlag: (attList == null || attList.isEmpty),
                  startday: _startDay, endday: _endDay, picid: widget?.picid,
                  hsns: hsns, cantManageHsns: cantManageHsns);
              if(StringUtils.isNotEmpty(result)){
                _viewModel.getMediaDetail(widget?.picid);
              }
            },
          )
        ],
      ),
    );
  }

  ///播放周期
  Widget _playTimeWidget(List<AttListBean> attList) {
    String startTime = "x月x日";
    String endTime = "x月x日";
    bool samePlayInterval = true;
    if(attList != null && attList.length > 0){
      if(StringUtils.isNotEmpty(attList[0].startday)&&StringUtils.isNotEmpty(attList[0].endday)){
        startTime = attList[0].startday;
        endTime = attList[0].endday;
        _startDay = attList[0].startday;
        _endDay = attList[0].endday;
        for(int i = 1; i < attList.length; i++){
          if(StringUtils.isNotEmpty(attList[i]?.endday) && DateTime.parse(endTime).millisecondsSinceEpoch <= DateTime.parse(attList[i].endday).millisecondsSinceEpoch){
            endTime = attList[i].endday;
            _endDay = attList[i].endday;
          }
          if(StringUtils.isNotEmpty(attList[i]?.startday) && DateTime.parse(startTime).millisecondsSinceEpoch >= DateTime.parse(attList[i].startday).millisecondsSinceEpoch){
            startTime = attList[i].startday;
            _startDay = attList[i].startday;
          }
        }
        startTime = DateUtil.getDateStrByDateTime(DateTime.parse(startTime), format: DateFormat.ZH_MONTH_DAY);
        if("9999-99-99" != endTime && "10007-06-0" != endTime){
          DateTime endDateTime = DateTime.parse(endTime);
          DateTime currentDateTime = DateTime.now();
          if(VgDateTimeUtils.yearIsEqual(endDateTime, currentDateTime)){
            endTime = DateUtil.getDateStrByDateTime(endDateTime, format: DateFormat.ZH_MONTH_DAY);
          }else{
            endTime = DateUtil.getDateStrByDateTime(endDateTime, format: DateFormat.ZH_YEAR_MONTH_DAY);
          }
        }else{
          endTime = "永久";
        }

        String tempStartTime = attList[0].startday;
        String tempEndTime = attList[0].endday;
        for(int i = 1; i < attList.length; i++){
          if(tempStartTime != attList[i].startday || tempEndTime != attList[i].endday){
            samePlayInterval = false;
            break;
          }else{
            tempStartTime = attList[i].startday;
            tempEndTime = attList[i].endday;
          }
        }
      }
    }else{
      DateTime startDay = DateTime.parse(DateUtil.getDateStrByDateTime(DateTime.now(), format: DateFormat.YEAR_MONTH_DAY));
      _startDay = DateUtil.getDateStrByDateTime(startDay, format: DateFormat.YEAR_MONTH_DAY);
      DateTime endDay = DateTime.fromMillisecondsSinceEpoch(startDay.millisecondsSinceEpoch
          + 14*24*3600*1000);
      _endDay = DateUtil.getDateStrByDateTime(endDay, format: DateFormat.YEAR_MONTH_DAY);
    }
    bool canAdjust = VgRoleUtils.isSuperAdmin(UserRepository.getInstance().getCurrentRoleId());
    int adminCount = 0;
    if(attList != null && attList.length > 0){
      attList.forEach((element) {
        if(("01" == element.adminflg)){
          adminCount++;
        }
      });
    }
    canAdjust = canAdjust || (adminCount == (attList?.length??0));
    return Visibility(
      visible: (("x月x日" != startTime) || ("x月x日" != endTime)),
      child: Container(
        height: 35,
        color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        padding: EdgeInsets.only(left: 15, right: 5),
        child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () async {
            // if(!canAdjust){
            //   return;
            // }
            Map<String, dynamic> resultMap = await SetPlayIntervalDialog.navigatorPushDialog(context, "设置播放周期", DateTime.parse(_startDay),
                DateTime.parse(_endDay),
                backup: ((attList?.length??0) >1)? (samePlayInterval?"设置后将应用于全部显示屏":"目前该文件在各显示屏的播放周期不一致，设置后将统一"):""
              // showTerminalRange: (attList?.length??0)>0
            );
            if(resultMap == null){
              return;
            }
            String startDayStr = resultMap[SetPlayIntervalDialog.RESULT_START_DAY_STR];
            String endDayStr = resultMap[SetPlayIntervalDialog.RESULT_END_DAY_STR];
            String hsns  = "";
            attList.forEach((element) {
              hsns += element.hsn;
              hsns += ",";
            });
            if(StringUtils.isNotEmpty(hsns)){
              hsns = hsns.substring(0, hsns.length-1);
            }
            _viewModel.updateMediaPlayInterval(context, widget?.picid, hsns, startDayStr, endDayStr, () {
              _viewModel.getMediaDetail(widget?.picid);
            });
          },
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Text(
                "播放周期：",
                style: TextStyle(
                  fontSize: 12,
                  color: ThemeRepository.getInstance().getTextBFC2CC_BFC2CC(),
                ),
              ),
              Text(
                startTime,
                style: TextStyle(
                    fontSize: 12,
                    color:ThemeRepository.getInstance().getPrimaryColor_1890FF()
                  // canAdjust?
                  // ThemeRepository.getInstance().getPrimaryColor_1890FF()
                  //     :ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                ),
              ),
              Text(
                " 至 ",
                style: TextStyle(
                  fontSize: 12,
                  color: ThemeRepository.getInstance().getTextBFC2CC_BFC2CC(),
                ),
              ),
              Text(
                endTime,
                style: TextStyle(
                    fontSize: 12,
                    color: ThemeRepository.getInstance().getPrimaryColor_1890FF()
                  // canAdjust?
                  // ThemeRepository.getInstance().getPrimaryColor_1890FF()
                  //     :ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                ),
              ),
              SizedBox(width: 3,),
              Container(
                alignment: Alignment.center,
                padding: EdgeInsets.only(top: 16, bottom: 15),
                child: canAdjust?
                Image.asset(
                  "images/icon_blue_arrow.png",
                  width: 7,
                  height: 4,
                ):Image.asset(
                  "images/icon_blue_arrow.png",
                  color: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                  width: 7,
                  height: 4,
                ),
              ),
              SizedBox(
                width: 10,
              ),
              Visibility(
                visible: !samePlayInterval,
                child: Text(
                  "（注：各终端不一致）",
                  style: TextStyle(
                    fontSize: 12,
                    color:
                    ThemeRepository.getInstance().getMinorYellowColor_FFB714(),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  ///终端列表
  Widget _terminalListWidget(List<AttListBean> attList) {
    return ListView.separated(
        itemCount: attList?.length ?? 0,
        padding: EdgeInsets.only(bottom: getNavHeightDistance(context)),
        keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
        shrinkWrap: true,
        physics: BouncingScrollPhysics(),
        itemBuilder: (BuildContext context, int index) {
          return _toListItemWidget(context, attList, index);
        },
        separatorBuilder: (BuildContext context, int index) {
          return SizedBox(
            height: 0,
          );
        });
  }

  Widget _toListItemWidget(
      BuildContext context, List<AttListBean> attList, int index) {
    AttListBean itemBean = attList[index];
    return ClickBackgroundWidget(
      onTap: () {
        TerminalDetailInfoPage.navigatorPush(context, itemBean?.hsn, router: MediaDetailPage.ROUTER);
      },
      child: Container(
        height: 64,
        child: Row(
          children: <Widget>[
            SizedBox(
              width: 15,
            ),
            _toPicWidget(itemBean),
            SizedBox(
              width: 12,
            ),
            Expanded(
              child: Container(
                height: 38,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Row(
                      children: [
                        Visibility(
                          visible: (StringUtils.isEmpty(itemBean?.terminalName) && StringUtils.isEmpty(itemBean?.sideNumber)&& StringUtils.isNotEmpty(itemBean?.hsn)),
                          child: Text(
                            // "硬件ID：",
                            "",
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                color: ThemeRepository.getInstance()
                                    .getTextMainColor_D0E0F7(),
                                fontSize: 15,
                                height: 1.2
                              // fontWeight: FontWeight.w600
                            ),
                          ),
                        ),
                        Expanded(
                          child: Text(
                            itemBean?.getTerminalName(index) ?? "终端显示屏${(index ?? 0) + 1}",
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                color: ThemeRepository.getInstance()
                                    .getTextMainColor_D0E0F7(),
                                fontSize: 15,
                                height: 1.2
                            ),
                          ),
                        ),
                      ],
                    ),
                    Text(
                      // "${itemBean?.attnum ?? 0}终端，共播放${itemBean?.playnum ?? 0}次",
                      StringUtils.isNotEmpty(itemBean?.position??"")?itemBean?.position:itemBean?.address??"-",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: VgColors.INPUT_BG_COLOR, fontSize: 12, height: 1.2),
                    )
                  ],
                ),
              ),
            ),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () async {
                if(!(itemBean?.canAdjust()??false)){
                  return;
                }
                Map<String, dynamic> resultMap = await SetPlayIntervalDialog.navigatorPushDialog(context, "设置播放周期",
                    DateTime.parse(itemBean?.startday??_startDay),
                    DateTime.parse(itemBean?.endday??_endDay),
                    showTerminalRange: (attList?.length??0)>1
                );
                if(resultMap == null){
                  return;
                }
                String startDayStr = resultMap[SetPlayIntervalDialog.RESULT_START_DAY_STR];
                String endDayStr = resultMap[SetPlayIntervalDialog.RESULT_END_DAY_STR];
                String showTerminalArrange = resultMap[SetPlayIntervalDialog.SHOW_TERMINAL_ARRANGE];
                String hsns = itemBean?.hsn??"";
                if("00" == showTerminalArrange){
                  hsns = "";
                  attList.forEach((element) {
                    if(element.canAdjust()){
                      hsns += element.hsn;
                      hsns += ",";
                    }
                  });
                  if(StringUtils.isNotEmpty(hsns)){
                    hsns = hsns.substring(0, hsns.length-1);
                  }
                }
                _viewModel.updateMediaPlayInterval(context, widget?.picid, hsns, startDayStr, endDayStr, () {
                  _viewModel.getMediaDetail(widget?.picid);
                });
              },
              child: Container(
                alignment: Alignment.topLeft,
                height: 64,
                padding: EdgeInsets.only(left:15, top: 13, right: 15),
                child: Text(
                  // ("永久播放" == (itemBean?.getResumePlayInterval()??"剩余0天"))?"永久播放"
                  //     :("已播放${itemBean?.getAlreadyPlayInterval()??"0天"}，${itemBean?.getResumePlayInterval()??"剩余0天"}"),
                  itemBean?.getPlayTimeString(),
                  style: TextStyle(
                      fontSize: 10,
                      color:
                      (itemBean?.canAdjust()??false)?
                      ThemeRepository.getInstance().getPrimaryColor_1890FF()
                          :ThemeRepository.getInstance().getHintGreenColor_5E687C()
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _toPicWidget(AttListBean itemBean) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(4),
      child: Container(
        width: 40,
        height: 40,
        color: Color(0xFF191E31),
        child: VgCacheNetWorkImage(
          itemBean?.terminalPicurl ?? "",
          imageQualityType: ImageQualityType.middleDown,
          errorWidget: Container(
            child: Image.asset(
              "images/icon_terminal_holder.png",
              fit: BoxFit.cover,
            ),
          ),
          placeWidget: Container(
            child: Image.asset(
              "images/termial_empty_place_holder_ico.png",
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
    );
  }
}

class MySliverDelegate extends SliverPersistentHeaderDelegate {
  MySliverDelegate({
    @required this.minHeight,
    @required this.maxHeight,
    @required this.child,
    @required this.shrinkOffsetFunc,
    this.stableWidget,
  });

  final double minHeight; //最小高度
  final double maxHeight; //最大高度
  final Widget child; //子Widget布局
  final Widget stableWidget; //
  final Function(double shrinkOffset) shrinkOffsetFunc; //

  @override
  double get minExtent => minHeight;

  @override
  double get maxExtent => Math.max(maxHeight, minHeight);

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    shrinkOffsetFunc.call(shrinkOffset);
    return SizedBox.expand(
      child: Container(
          color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
          child: Column(
            children: <Widget>[Expanded(child: child), stableWidget],
          )),
    );
  }

  @override //是否需要重建
  bool shouldRebuild(MySliverDelegate oldDelegate) {
    return maxHeight != oldDelegate.maxHeight ||
        minHeight != oldDelegate.minHeight ||
        child != oldDelegate.child;
  }
}
